#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Author       : Abmer
# @Date         : 2019-08-06 10:09:50
# @Link         : https://gitee.com/edrik
# @Modified by  : Amber
# @Modified at  : 2019-08-31 09:58:43
# @Version      : v.0.1

from .context import GlobalKV as gl
from .capi.mbapi import api
from .capi.mbdef import wkeWindowType
from .callback import *
from .nativejs import *
from .script import bind_fn_as_javascript
from .error import WkeError


class BaseWindow:
    _initialized = False

    def __init__(self):
        # api.wekInit()
        api.wkeInitialize()
        self.webview = None
        self.hwnd = None

    def __del__(self):

        pass

    def mainloop(self):
        ctypes.windll.user32.SetProcessDPIAware(2)

        msg = ctypes.wintypes.MSG()
        # lpmsg = ctypes.byref(msg)
        lpmsg = ctypes.pointer(msg)

        while ctypes.windll.user32.GetMessageW(lpmsg, 0, 0, 0) > 0:
            ctypes.windll.user32.TranslateMessage(lpmsg)
            ctypes.windll.user32.DispatchMessageW(lpmsg)
        api.wkeFinalize()
        return int(msg.wParam)

    def _create_webview(self, pos, size):
        if not BaseWindow._initialized:
            # BaseWindow._initialized = True
            # return
            pass

        x, y = pos
        w, h = size

        #  get client screen rect
        #
        webview = gl.webview = api.wkeCreateWebWindow(wkeWindowType.WKE_WINDOW_TYPE_POPUP, None, x, y, w, h)
        if not webview:
            raise WkeError('Could not create webview')
        # webview = gl.webview = api.wkeCreateWebWindow(wkeWindowType.WKE_WINDOW_TYPE_TRANSPARENT, None, x, y, w, h)

        # gl.hwnd =api.wkeGetHostHWND(webview)
        gl.hwnd = api.wkeGetWindowHandle(webview)
        gl.exstate = api.wkeGlobalExec(webview)
        gl.main_frame = api.wkeWebFrameGetMainFrame(webview)
        #
        api.wkeMoveToCenter(webview)
        api.wkeSetWindowTitleW(webview, self.title)
        # event
        api.wkeOnNavigation(webview, wkeNavigationCallback, 0)
        api.wkeOnTitleChanged(webview, wkeTitleChangedCallback, 0)
        # api.wkeOnDocumentReady(webview, wkeDocumentReadyCallback, 0)
        api.wkeOnDocumentReady2(webview, wkeDocumentReady2Callback, 0)
        api.wkeOnDidCreateScriptContext(webview, wkeDidCreateScriptContextCallback, 0)
        # api.wkeOnCreateView(webview, wkeCreateViewCallback, 0)
        api.wkeOnLoadUrlBegin(webview, wkeLoadUrlBeginCallback, 0)
        api.wkeOnLoadUrlEnd(webview, wkeLoadUrlEndCallback, 0)
        api.wkeOnLoadingFinish(webview, wkeLoadingFinishCallback, 0)

        api.wkeOnWindowClosing(webview, wkeWindowClosingCallback, 0)
        api.wkeOnWindowDestroy(webview, wkeWindowDestroyCallback, 0)

        api.wkeShowWindow(webview, True)  # show window

        return webview

    def bind_fn_as_javascript(self, js_fname, py_fn):
        bind_fn_as_javascript(js_fname, py_fn)
